#!/usr/bin/env bash
set -euxo pipefail

git config user.name mise-en-dev
git config user.email release@mise.jdx.dev

cur_version="$(cargo pkgid mise | cut -d# -f2)"
if ! curl https://crates.io/api/v1/crates/mise | jq -r '.versions[0].num' | grep -q "$cur_version"; then
	echo "Releasing $cur_version"
	cargo publish
	changelog="$(git cliff --tag "v$cur_version" --strip all --unreleased)"
	changelog="$(echo "$changelog" | tail -n +3)"
	git tag "v$cur_version" -s -m "$changelog"
	git push --tags
	gh release create "v$cur_version" --title "v$cur_version" --notes "$changelog" --draft
	exit 0
fi

git submodule update --remote

year="$(date +%Y)"
month="$(date +%-m)"
if echo "$cur_version" | grep -e "^$year\.$month\."; then
	cargo set-version --bump patch
elif echo "$cur_version" | grep -e "^$year\."; then
	cargo set-version --bump minor
else
	cargo set-version "$year.1.0"
fi

version="$(cargo pkgid mise | cut -d# -f2)"
git cliff --tag "v$version" -o CHANGELOG.md
changelog="$(git cliff --tag "v$version" --unreleased --strip all)"
changelog="$(echo "$changelog" | tail -n +3)"
sed -i.bak "s/^[0-9]\+\.[0-9]\+\.[0-9]\+\(-rc\.[0-9]\+\)\? macos-arm64 (a1b2d3e [0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\})$/$version macos-arm64 (a1b2d3e $(date +%Y-%m-%d))/" README.md
sed -i.bak "s/^Version: [0-9]\+\.[0-9]\+\.[0-9]\+\(-rc\.[0-9]\+\)\?$/Version: $version/" packaging/rpm/mise.spec
sed -i.bak "s/version = \"[0-9]\+\.[0-9]\+\.[0-9]\+\(-rc\.[0-9]\+\)\?\";$/version = \"$version\";/" default.nix

mise run render ::: lint-fix

mise up
# cargo update
git add \
	Cargo.lock \
	Cargo.toml \
	CHANGELOG.md \
	README.md \
	aqua-registry \
	default.nix \
	packaging/rpm/mise.spec \
	mise.usage.kdl \
	completions \
	man/
git clean -df
git checkout -B release
git commit -m "chore: release $version"
git push origin release --force

if [[ "$(gh pr list --label release)" == "" ]]; then
	gh pr create --title "chore: release $version" --body "$changelog" --label "release" --head release
else
	gh pr edit --title "chore: release $version" --body "$changelog"
fi
